package com.hsogoo.avatar.executor;

import java.util.Iterator;
import java.util.ServiceLoader;

import com.hsogoo.avatar.serialization.Serializer;
import com.hsogoo.avatar.utils.ExceptionUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by za-huangsaigang on 2018/10/23.
 */
@Slf4j
public class AvatarExecutors {

    private static final AvatarExecutor providerExecutor;
    private static final AvatarExecutor consumerExecutor;

    static {
        ExecutorFactory factory;
        try {
            ServiceLoader<ExecutorFactory> loader = ServiceLoader.load(ExecutorFactory.class);
            Iterator<ExecutorFactory> iterator = loader.iterator();
            if (!iterator.hasNext()) {
                throw new IllegalStateException(String.format(
                        "no implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
                        ExecutorFactory.class.getName()));
            }
            factory = iterator.next();
        } catch (Throwable t) {
            log.warn("Failed to load provider's executor factory [{}], cause: {}, " +
                    "[ThreadPoolExecutorFactory] will be used as default.", "factoryName", ExceptionUtil.getDetailMessage(t));

            factory = new ThreadPoolExecutorFactory();
        }

        providerExecutor = factory.newExecutor(ExecutorFactory.Target.PROVIDER, "avatar-provider-processor");
        consumerExecutor = factory.newExecutor(ExecutorFactory.Target.CONSUMER, "avatar-consumer-processor");
    }

    public static AvatarExecutor providerExecutor() {
        return providerExecutor;
    }

    public static AvatarExecutor consumerExecutor() {
        return consumerExecutor;
    }

    public static void providerExecute(Runnable r) {
        providerExecutor.execute(r);
    }

    public static void consumerExecute(Runnable r) {
        consumerExecutor.execute(r);
    }
}
